package com.hp.gxw.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hp.gxw.constant.TypeEnum;
import com.hp.gxw.entity.*;
import com.hp.gxw.mapper.SaleOrderDetailsMapper;
import com.hp.gxw.mapper.SaleOrderMapper;
import com.hp.gxw.mapper.SaleOrderProcessMapper;
import com.hp.gxw.mapper.SettlementOrderMapper;
import com.hp.gxw.service.ISettlementOrderDetailsService;
import com.hp.gxw.service.ISettlementOrderProcessService;
import com.hp.gxw.service.ISettlementOrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author huangping
 * @since 2023-10-17
 */
@Service
public class SettlementOrderServiceImpl extends ServiceImpl<SettlementOrderMapper, SettlementOrder> implements ISettlementOrderService {

    @Autowired
    private ISettlementOrderDetailsService iSettlementOrderDetailsService;

    @Autowired
    private ISettlementOrderProcessService iSettlementOrderProcessService;

    @Resource
    private SettlementOrderMapper settlementOrderMapper;

    @Resource
    private SaleOrderMapper saleOrderMapper;

    @Resource
    private SaleOrderProcessMapper saleOrderProcessMapper;

    @Override
    public void saveInfo(SettlementOrder settlementOrder, List<SettlementOrderDetails> settlementOrderDetailsList) {
        save(settlementOrder);
        for(SettlementOrderDetails settlementOrderDetails : settlementOrderDetailsList){
            settlementOrderDetails.setMasterId(settlementOrder.getId());
            iSettlementOrderDetailsService.save(settlementOrderDetails);
            List<SettlementOrderProcess> processList = settlementOrderDetails.getProcess();
            for(SettlementOrderProcess settlementOrderProcess : processList){
                settlementOrderProcess.setDetailsId(settlementOrderDetails.getId());
            }
            iSettlementOrderProcessService.saveBatch(processList);
        }
    }

    @Override
    public Page<Map<String, Object>> getSettlementReportPage(Page<Object> page, QueryWrapper<SaleOrder> ew) {
        return settlementOrderMapper.getSettlementReportPage(page,ew);
    }

    @Override
    public List<Map<String, Object>> getSettlementReportList(QueryWrapper<SaleOrder> ew) {
        return settlementOrderMapper.getSettlementReportList(ew);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(JSONObject json) {

        //判断内部订单号是否存在
        String orderNo = json.getString("orderNo");
        if (StringUtils.isEmpty(orderNo)){
            throw new RuntimeException("内部订单号未填写！");
        }
        long count = count(Wrappers.lambdaQuery(SettlementOrder.class).eq(SettlementOrder::getOrderNo, orderNo));
        if (count > 0){
            throw new RuntimeException("内部订单号已存在！");
        }
        //查询销售订单，补充其他信息
        SaleOrder saleOrder = saleOrderMapper.selectOne(Wrappers.lambdaQuery(SaleOrder.class).eq(SaleOrder::getOrderNo, json.getString("saleOrderNo")));
        SettlementOrder settlementOrder = new SettlementOrder();
        BeanUtil.copyProperties(saleOrder, settlementOrder);
        BeanUtil.copyProperties(json, settlementOrder);
        settlementOrder.setStatus(false);
        settlementOrder.setId(null);
        Date createTime = json.getDate("createTime");
        settlementOrder.setDdate(createTime);
        settlementOrder.setDverifydate(createTime);
        settlementOrder.setDverifysystime(createTime);
        settlementOrder.setCustom(true);
        settlementOrder.setCreateTime(new Date());
        save(settlementOrder);

        JSONArray details = json.getJSONArray("details");
        for (Object detail : details) {
            JSONObject detailObj = (JSONObject) detail;
            saveDetails(detailObj, settlementOrder);
        }

    }

    private void saveDetails(JSONObject detailObj, SettlementOrder settlementOrder) {
        //添加明细
        SettlementOrderDetails orderDetails = new SettlementOrderDetails();
        BeanUtil.copyProperties(detailObj, orderDetails);
        orderDetails.setMasterId(settlementOrder.getId());
        orderDetails.setDetailId(detailObj.getString("id"));
        orderDetails.setCompletFlag(false);
        iSettlementOrderDetailsService.saveOrUpdate(orderDetails);
        //获取明细对应的工序
        JSONArray process = detailObj.getJSONArray("process");
        //查询销售订单工序
        for (Object pro : process) {
            SettlementOrderProcess orderProcess = new SettlementOrderProcess();
            BeanUtil.copyProperties(pro, orderProcess);
            orderProcess.setDetailsId(orderDetails.getId());
            iSettlementOrderProcessService.saveOrUpdate(orderProcess);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void upd(JSONObject json) {
        String orderNo = json.getString("orderNo");
        SettlementOrder settlementOrder = getOne(Wrappers.lambdaQuery(SettlementOrder.class).eq(SettlementOrder::getOrderNo, orderNo));
        if (null == settlementOrder){
            throw new RuntimeException("内部订单号不存在！");
        }
        BeanUtil.copyProperties(json, settlementOrder);
        Date createTime = json.getDate("createTime");
        settlementOrder.setDdate(createTime);
        settlementOrder.setDverifydate(createTime);
        settlementOrder.setDverifysystime(createTime);
        settlementOrder.setCustom(true);
        settlementOrder.setCreateTime(new Date());
        updateById(settlementOrder);

        //先删除指定表体数据
//        List<SettlementOrderDetails> list = iSettlementOrderDetailsService.list(Wrappers.lambdaQuery(SettlementOrderDetails.class).eq(SettlementOrderDetails::getMasterId, settlementOrder.getId()));
//        if (!list.isEmpty()){
//            List<Long> collect = list.stream().map(SettlementOrderDetails::getId).collect(Collectors.toList());
//            //删除工序
//            iSettlementOrderProcessService.remove(Wrappers.lambdaQuery(SettlementOrderProcess.class).in(SettlementOrderProcess::getDetailsId,collect));
//            iSettlementOrderDetailsService.removeBatchByIds(list);
//        }

        //新增
        JSONArray details = json.getJSONArray("details");
        for (Object detail : details) {
            JSONObject detailObj = (JSONObject) detail;
            saveDetails(detailObj, settlementOrder);
        }

    }
}
